#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
#if UNITY_EDITOR
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace Neatly.UI
{
    public class UIUtility
    {
        #region Image
        public static bool IsEmptyImage(NImage img)
        {
            return img.sprite == null && string.IsNullOrEmpty(img.SpriteName) && img.GetMaterial() == null;
        }
        public static bool IsMissing(NImage img)
        {
            return img.sprite == null || string.IsNullOrEmpty(img.SpriteName) || img.GetMaterial() == null ||
                   img.SpriteName != img.sprite.name;
        }
        /// <summary>
        /// 设置Sprite
        /// </summary>
        /// <param name="img"></param>
        /// <param name="spriteName"></param>
        public static void SetImageSprite(NImage img, string spriteName)
        {
            Material mat;
            Sprite sprite = FindImageSprite(spriteName, img.UseBlur, out mat);
            SetImageSprite(img, sprite, mat);
        }
        public static void SetImageSprite(NImage img, Sprite sprite, Material material)
        {
            img.SetSprite(string.Empty, sprite);
            img.SetMaterial(material);
            if (sprite)
            {
                img.SpriteName = sprite.name;
            }
        }
        /// <summary>
        /// 查找Sprite
        /// </summary>
        /// <param name="spriteName"></param>
        /// <param name="useBlur"></param>
        /// <param name="mat"></param>
        /// <returns></returns>
        public static Sprite FindImageSprite(string spriteName, bool useBlur, out Material mat)
        {
            string path = "Assets/data/ui/atlas_tp";
            if (Directory.Exists(path))
            {
                var files = Directory.GetFiles(path);
                foreach (var fileName in files)
                {
                    if (!fileName.EndsWith(".png")) continue;
                    var sprites = AssetDatabase.LoadAllAssetsAtPath(fileName);
                    foreach (var sprite in sprites)
                    {
                        if (!sprite.name.Equals(spriteName)) continue;
                        string textureName = fileName.Split('.')[0];
                        string atlasName = textureName.Substring(0, textureName.Length - 1);
                        atlasName = useBlur ? $"{atlasName}mat_blur.mat" : $"{atlasName}mat.mat";
                        mat = AssetDatabase.LoadAssetAtPath<Material>(atlasName);
                        return sprite as Sprite;
                    }
                }
            }
            mat = null;
            return null;
        }
        public static bool FixImageSprite(NImage img, string spriteName, string sourceName = "")
        {
            Material mat;
            Sprite sp = FindImageSprite(spriteName, img.UseBlur, out mat);
            if (sp == null)
            {
                Debug.LogError(string.Format("Sprite找不到:{0} Prefab:{1} Item:{2}", spriteName, sourceName, img.name));
                return false;
            }
            SetImageSprite(img, sp, mat);
            return true;
        }
        public static bool FixSpriteMiss(GameObject source)
        {
            bool isRepleace = false;
            NImage[] images = source.GetComponentsInChildren<NImage>(true);
            foreach (var img in images)
            {
                if (img.UseSpritePacker) continue;
                if (IsEmptyImage(img)) continue;
                if (IsMissing(img))
                {
                    string spriteName = null;
                    if (img.sprite != null)
                    {
                        spriteName = img.sprite.name;
                    }
                    else if (!string.IsNullOrEmpty(img.SpriteName))
                    {
                        spriteName = img.SpriteName;
                    }
                    if (string.IsNullOrEmpty(spriteName))
                    {
                        Debug.LogError(string.Format("[Error] Prefab:{0} Item:{1}", source.name, img.name));
                    }
                    FixImageSprite(img, img.SpriteName, source.name);
                }
                if (!string.IsNullOrEmpty(img.SpriteName) && (img.sprite == null))
                {
                    Material mat;
                    Sprite sp = FindImageSprite(img.SpriteName, img.UseBlur, out mat);
                    if (sp == null)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("[prefab]:")
                            .Append(source.name)
                            .Append(" [Item]:")
                            .Append(img.name)
                            .Append("[sprite]:")
                            .Append(img.SpriteName);
                        Debug.LogError(sb.ToString());
                    }
                    else
                    {
                        SetImageSprite(img, sp, mat);
                        isRepleace = true;
                    }
                }
            }
            return isRepleace;
        }
        public static bool ImageToUseTexturePacker(GameObject source)
        {
            bool isRepleace = false;
            NImage[] images = source.GetComponentsInChildren<NImage>(true);
            foreach (var img in images)
            {
                if (img.UseSpritePacker && img.sprite)
                {
                    Sprite sp = FindImageSprite(img.sprite.name, img.UseBlur, out _);
                    if (sp == null)
                    {
                        Debug.LogError("该Sprite可能未被打入图集请检查!!!" + img.sprite.name);
                        return isRepleace;
                    }
                    img.UseSpritePacker = false;
                    if (FixImageSprite(img, img.sprite.name, source.name))
                    {
                        isRepleace = true;
                    }
                }
            }
            return isRepleace;
        }
        #endregion
    }
}
#endif